package com.gw.yunke.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gw.yunke.dao.CourseMapper;
import com.gw.yunke.dao.UserMapper;
import com.gw.yunke.domain.Course;
import com.gw.yunke.domain.User;
import com.gw.yunke.domain.UserExample;
import com.gw.yunke.domain.dto.CourseModifyReq;
import com.gw.yunke.domain.dto.UserReq;
import com.gw.yunke.domain.dto.UserSimpleInfo;
import com.gw.yunke.domain.dto.UserToken;
import com.gw.yunke.exception.LoginInfoException;
import com.gw.yunke.exception.TokenTimeOutExeption;
import com.gw.yunke.exception.UnLoginException;
import com.gw.yunke.service.ICourseService;
import com.gw.yunke.service.IInstituteService;
import com.gw.yunke.service.IUserService;
import com.gw.yunke.utils.EncryptUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;

import static com.gw.yunke.domain.dto.ResultData.OK;

@Service
public class UserServiceImpl implements IUserService {

  private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);

  @Autowired
  private UserMapper userMapper;
  @Autowired
  private IInstituteService instituteService;
  @Autowired
  private CourseMapper courseMapper;


  @Override
  public User getUserInfoByToken(String token) throws Exception {
    try {
      UserReq userReq = new UserReq();
      userReq.setEmail(token);
      List<User> userList = getUserByExample(userReq);
      UserToken userToken;
      try {
        String jsonString = EncryptUtils.sha256HMACDecode(token, "yunke");
        System.out.println("***********objectString="+jsonString);
        userToken = new ObjectMapper().readValue(jsonString, UserToken.class);

      } catch (Exception e) {
        throw new LoginInfoException("登录信息有误");
      }

      if (userToken == null || userToken.getEndTime() < new Date().getTime()) {
        throw new TokenTimeOutExeption("登录信息过期，请重新登录");
      }
      User user = new User();
      BeanUtils.copyProperties(userToken,user);
      return user;
    } catch (Exception e) {
      throw e;
    }
  }

  @Override
  public User getUserById(Long userId) {
    return null;
  }

  @Override
  public List<User> getUserByExample(UserReq req) {
    UserExample example = new UserExample();
    UserExample.Criteria criteria = example.createCriteria();
    if (!StringUtils.isEmpty(req.getEmail())) {
      criteria.andEmailEqualTo(req.getEmail());
    }
    if (!StringUtils.isEmpty(req.getName())) {
      criteria.andNameEqualTo(req.getName());
    }

    return userMapper.selectByExample(example);
  }

  @Override
  public int saveUser(User user) {

    int result = userMapper.insertSelective(user);
    return result;
  }

  @Override
  public int updateUser(User user) {
    return 0;
  }

  @Override
  public int checkLogin(String token,User loginUser) throws Exception {
    if(StringUtils.isEmpty(token)){

      throw new UnLoginException("未登录");
    }
    User user = getUserInfoByToken(token);
    if(user == null){

      throw  new LoginInfoException("登录信息有误");
    }
    BeanUtils.copyProperties(user,loginUser);
    return 1;
  }

  @Override
  public UserSimpleInfo buildUserSimpleInfo(User user) {
    UserSimpleInfo userSimpleInfo = new UserSimpleInfo();

    userSimpleInfo.setName(user.getName());
    userSimpleInfo.setExp("7643");
    userSimpleInfo.setType(user.getType() == true ? (byte)1 : (byte)0);
    userSimpleInfo.setRecentLookCourseName("计算机网络");
    userSimpleInfo.setRecentLookPartName("2-1 基本概念");
    userSimpleInfo.setRecentLookUrl("/yunke/course/video/1");
    userSimpleInfo.setImageRequestUrl("/yunke/course/image/2");
    String specialtyName = instituteService.getSpecialtyNameByCode(user.getSpecialtyCode());
    userSimpleInfo.setSpecialtyName(specialtyName);

    return userSimpleInfo;
  }

  @Override
  public boolean checkCreatePermission(User user, Long courseId) {
    Course course = courseMapper.selectByPrimaryKey(courseId);
    return user.getId() == course.getUserId() || user.getId().equals(course.getUserId());
  }
}
